package logic

import (
	"context"
	"ture/models/mysql"

	"ture/turerpc/internal/svc"
	"ture/turerpc/turerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type TrueAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTrueAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TrueAddLogic {
	return &TrueAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *TrueAddLogic) TrueAdd(in *turerpc.TrueAddRequest) (*turerpc.TrueAddResponse, error) {
	// todo: add your logic here and delete this line

	begin := mysql.DB.Debug().Begin()
	var brand mysql.Brand
	begin.Where("name=?", in.BrandName).Find(&brand)
	if brand.ID == 0 {

		brand = mysql.Brand{

			Name: in.Name,
		}
		err := mysql.DB.Debug().Create(&brand).Error
		if err != nil {
			return nil, err
			begin.Rollback()
		}
	}
	var class mysql.Class
	begin.Where("name=?", in.ClassName).Find(&class)
	if class.ID == 0 {
		class = mysql.Class{

			Name: in.ClassName,
		}
		err := begin.Create(&class).Error
		if err != nil {
			return nil, err
			begin.Rollback()
		}
	}
	m := mysql.True{

		Title:   in.Title,
		Name:    in.Name,
		Price:   float64(in.Price),
		BrandId: in.BrandId,
		ClassId: in.ClassId,
	}
	err := begin.Create(&m).Error
	if err != nil {
		return nil, err
		begin.Rollback()
	}
	begin.Commit()
	return &turerpc.TrueAddResponse{
		TrueId: int64(m.ID),
	}, nil

}
